var lastStep; // dernière étape, pour accès direct aux étapes
var currentStep;

$(document).ready(function() {
	
    var formApp = new Array();
    var formPol = new Array();
    var adressesEnt = new Array();
    var personnalInfoEdited = false;
    var generated = false;
    var stepModified = new Array();
    stepModified[2] = false;
    stepModified[3] = false;
    stepModified[4] = false;
    var dataHtml;
    

    window.location.hash = "etape1";
    currentStep = 1;
    $("li#step1").wrap("<a href='' rel='1' />");
    
    $(window).scrollTop(97);
    
    $("div#step4").bind("editor", function () {
    	$("#test").cleditor();
    });
    
    $("button.nextStep").click(function(e) {
    	   e.preventDefault();   	   
    });
    
    $("button.prevStep").click(function(e) {
 	   e.preventDefault();
 	  //$(window).scrollTop(97);
    });
    
    $("ul#steps a").live('click', function(e) {
    	e.preventDefault();
    });
    
    /**
     * Autocomplete sur formule d'ouverture et de politesse
     */
    $.getJSON('../form/list/app', function(data) {
        text = eval(data);
        $(text).each(function () {
            formApp.push(this.text);
        });
        
        $("#letter_add_ouv").autocomplete({
            source: formApp,
            minLength : 0
        });
    });
    
    $.getJSON('../form/list/pol', function(data) {
        text = eval(data);
        $(text).each(function () {
            formPol.push(this.text);
        });
        
        $("#letter_add_ferm").autocomplete({
            source: formPol,
            minLength : 0
        });
    });
    
    /**
     * Autocomplete sur adresse d'entreprise (destinataire)
     */
    $.getJSON('../adressesEnt/list', function(data) {
        tab = eval(data);
        $(tab).each(function () {
        	var adr = new Object();
        	adr["value"] = this.value;
        	adr["label"] = this.label;
        	adr["compNom1"] = this.compNom1;
        	adr["compNom2"] = this.compNom2;
        	adr["adresse"] = this.adresse;
        	adr["cp"] = this.cp;
        	adr["ville"] = this.ville;
        	adressesEnt.push(adr);
        });
        
        $("#letter_add_nomDest").autocomplete({
            source: adressesEnt,
            minLength : 0,
            select: function(event, ui) {           	
            	$("#letter_add_nomDest").val(ui.item["value"]);
            	$("#letter_add_compNomDest1").val(ui.item["compNom1"]);
            	$("#letter_add_compNomDest2").val(ui.item["compNom2"]);
            	$("#letter_add_adresseDest").val(ui.item["adresse"]);
            	$("#letter_add_cpDest").val(ui.item["cp"]);
            	$("#letter_add_villeDest").val(ui.item["ville"]);
            	return false;
            }
        });
    });
    
    /**
     * Autocomplete sur nom de la ville à partir du code postal
     */
    $("#letter_add_cpDest").blur(function() {
    	
    	var reg = new RegExp('^[0-9]{5}$', 'i');
    	var cp = $(this).val();
    	if (reg.test(cp)) {
    		$("#letter_add_villeDest").val("Veuillez patienter ...");
    		$.getJSON('../cp/list/' + cp, function(data) {
    			var villes = eval(data);
    			var input = $("#letter_add_cpDest");
    			var nbvilles = villes.length;
    			if (nbvilles > 1) {
        			var select = "<select id='letter_add_villeDest' name='letter_add[villeDest]' >";
        			$(villes).each(function () {
        				select += "<option>" + this.commune + "</option>";
        			});
        			select += "</select>";
        			$("#letter_add_villeDest").replaceWith(select);
    			} else if (nbvilles == 1) {
    				var select = "<input type='text' id='letter_add_villeDest' name='letter_add[villeDest]' value>";
    				$("#letter_add_villeDest").replaceWith(select);
    				$(villes).each(function () {
    					var ville = this.commune;
    					$("#letter_add_villeDest").val(ville);
    				});
    			} else {
    				var select = "<input type='text' id='letter_add_villeDest' name='letter_add[villeDest]' value>";
    				$("#letter_add_villeDest").replaceWith(select);
    				$("#letter_add_villeDest").val("");
    			}    			
        	});
    	} else {
    		displayErrorMessage("letter_add", "cpDest", "Code postal invalide");
    	}   	
    });

    $("a#ouv").click(function() {
                // close if already visible
                if ($("#letter_add_ouv").autocomplete( "widget" ).is( ":visible" ) ) {
                        $("#letter_add_ouv").autocomplete( "close" );
                        return;
                }

                // work around a bug (likely same cause as #5265)
                $(this).blur();

                // pass empty string as value to search for, displaying all results
                $("#letter_add_ouv").autocomplete( "search", "" );
                $("#letter_add_ouv").focus();
    });
    
    $("a#ferm").click(function() {
            // close if already visible
            if ($("#letter_add_ferm").autocomplete( "widget" ).is( ":visible" ) ) {
                    $("#letter_add_ferm").autocomplete( "close" );
                    return;
            }

            // work around a bug (likely same cause as #5265)
            $(this).blur();

            // pass empty string as value to search for, displaying all results
            $("#letter_add_ferm").autocomplete( "search", "" );
            $("#letter_add_ferm").focus();
    });
    
    /**
     * Fonctions liées au formulaire d'adresse de l'expéditeur
     */
    
    $("form#lettral_user_personnalProfile input").change(function() {
    	personnalInfoEdited = true;
    });
    
    /**
     * Surveillance des modifications apportées à chaque étape afin de savoir si on doit valider de nouveau
     */
    $("form#letter_add div#step2 input").change(function() {
    	stepModified[2] = true;
    });
    
    $("form#letter_add div#step3 input").change(function() {
    	stepModified[3] = true;
    });
    
    $("form#letter_add div#step4 input").change(function() {
    	stepModified[4] = true;
    });
    
    /**
     * Pièces jointes
     */
    $("img.add").click(function() {
    	var div = $(this).closest("div"); // div courant
    	var num = parseInt($(div).attr("rel"));
    	if (num == 1 || num == 2) {
    		$("div.pj[rel=" + (num+1) + "]").fadeIn(300);
    	}  	
    });
    
    $("img.delete").click(function() {
    	var div = $(this).parent("div");
    	if ($(div).attr("rel") == 2 || $(div).attr("rel") == 3) {
    		$(div).fadeOut(300);
    		$(div).children("input").val("");
    	}  	
    });
    
    /**
     * Sélection de la date d'envoi
     */  
    $.datepicker.regional['fr'] = {
    		closeText: 'Fermer',
    		prevText: '&#x3c;Préc',
    		nextText: 'Suiv&#x3e;',
    		currentText: 'Courant',
    		monthNames: ['Janvier','Février','Mars','Avril','Mai','Juin',
    		'Juillet','Août','Septembre','Octobre','Novembre','Décembre'],
    		monthNamesShort: ['Jan','Fév','Mar','Avr','Mai','Jun',
    		'Jul','Aoû','Sep','Oct','Nov','Déc'],
    		dayNames: ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'],
    		dayNamesShort: ['Dim','Lun','Mar','Mer','Jeu','Ven','Sam'],
    		dayNamesMin: ['Di','Lu','Ma','Me','Je','Ve','Sa'],
    		weekHeader: 'Sm',
    		dateFormat: 'dd/mm/yy',
    		firstDay: 1,
    		isRTL: false,
    		showMonthAfterYear: false,
    		yearSuffix: ''};
    $.datepicker.setDefaults($.datepicker.regional['fr']);
    
    var date = new Date();
    var formatedDate;
    if (date.getDate() < 10) {
    	formatedDate = '0' + date.getDate() + '/';
    } else {
    	formatedDate = date.getDate() + '/';
    }
    if (date.getMonth() < 10) {
    	formatedDate += '0' + (date.getMonth()+1) + '/';
    } else {
    	formatedDate += (date.getMonth()+1) + '/';
    } 
    formatedDate += date.getFullYear();
    $("#letter_add_dateEcriture").val(formatedDate);
    $("#letter_add_dateEcriture").datepicker();
    
    /**
     * Evènement de clic sur une étape (barre supérieure)
     */
    $("ul#steps a").live('click', function() {
    	var hash = window.location.hash;
    	var originStep = hash.substr(hash.length-1, 1);
    	var destStep = $(this).attr('rel');
    	
    	if (destStep == originStep)
    		return false;
    	
    	if (originStep == 1) {
    		if (personnalInfoEdited) {
				if (!validate('lettral_user_personnalProfile')) {
					return false;
				}
				$.fancybox.showActivity();   
				$.ajax({ 
	                    type: "POST", 
	                    data: $('#lettral_user_personnalProfile').serialize(), 
	                    url: '../user/modifierinfoperso',
	                    success: function(data) {
	                    	$.fancybox.hideActivity();
	                    	var response = eval(data);
	                    	if (response.status == "success") {
	                    		personnalInfoEdited = false;
	                    		goToStep(destStep, 1);
	                    	}
	                    	else {
	                    		$(response).each(function () {
	                    			displayErrorMessage('lettral_user_personnalProfile', this.id, this.message);
	                        });
	                    	}
	                    } 
	            });
				return false;
			} else {
				goToStep(destStep, 1);
			}
    	}
    	if (destStep == 5) {
    		$.fancybox.showActivity(); 
    		$.ajax({ 
                type: "POST", 
                data: $('form#letter_add').serialize(), 
                url: $('form#letter_add').attr('action'),
                success: function(data) {
                	$.fancybox.hideActivity();
                	var response = eval(data);
                	if (response.status == "success") {
                		currentStep = 6;
                		if (currentStep > lastStep) lastStep = currentStep;
                		$("#step5 div#success").show();
                	}
                	else {
            			console.log(response);
                		$(response).each(function () {
                			if (this.message == 'generation') {
                				$("#step5 div#error").show();
                			} else {
                				displayErrorMessage('letter_add', this.id, this.message);
                			}
                		});
                	}
                	goToStep(destStep, originStep);
                },
                error: function(xhr, textStatus, errorThrown){
                }					
			});
    	}	
    	else {    	
	    	var valid = validate('step' + originStep);
    		if (destStep > originStep && !valid) {
				return false;
			} else if (destStep < originStep && stepModified[originStep]) {
				if (valid) {
					stepModified[originStep] = false;
				} else {
					return false;
				}
			}
	    	goToStep(destStep, originStep);
	    	return false;
    	} 
    });
    
    /**
     * Evènements de passage d'une étape à l'autre
     */
    $("button.nextStep").click(function() {
    	var currentStep = parseInt($(this).attr('rel')-1);
    	switch (currentStep) {
			case 1:
				currentStep = 1;
				lastStep = 1;
				if (personnalInfoEdited) {
					if (!validate('lettral_user_personnalProfile')) {
						break;
					}
					$.fancybox.showActivity();   
					$.ajax({ 
		                    type: "POST", 
		                    data: $('#lettral_user_personnalProfile').serialize(), 
		                    url: '../user/modifierinfoperso',
		                    success: function(data) {
		                    	$.fancybox.hideActivity();
		                    	var response = eval(data);
		                    	if (response.status == "success") {
		                    		personnalInfoEdited = false;
		                    		nextStep(2);
		                    		currentStep = 2;
		                    		if (currentStep > lastStep) lastStep = currentStep;
		                    	}
		                    	else {
		                    		$(response).each(function () {
		                    			displayErrorMessage('lettral_user_personnalProfile', this.id, this.message);
		                        });
		                    	}
		                    } 
		            });
				} else {
					nextStep(2);
					currentStep = 2;
            		if (currentStep > lastStep) lastStep = currentStep;
				}
				break;
			case 2:
				if (!validate('step2')) {
					break;
				}
				stepModified[2] = false; 
				nextStep(3);
				currentStep = 3;
        		if (currentStep > lastStep) lastStep = currentStep;
        		break;
			case 3:
				if (!validate('step3')) {
					break;
				}
				stepModified[3] = false;
				nextStep(4);
				currentStep = 4;
        		if (currentStep > lastStep) lastStep = currentStep;
        		break;
			case 4:
				if (!validate('step4')) {
					break;
				}
				stepModified[4] = false;
				currentStep = 5;
        		if (currentStep > lastStep) lastStep = currentStep;
				$.fancybox.showActivity();
				var url = $('form#letter_add').attr('action');
				var action = $(this).attr('id');
				if (action == 'save') {
					url += "/false";
				} 
				$.ajax({ 
                    type: "POST", 
                    data: $('form#letter_add').serialize(), 
                    url: url,
                    success: function(data) {
                    	$.fancybox.hideActivity();
                    	var response = eval(data);
                    	if (response.status == "success") {
                    		if (action == 'save') {
                    			window.location.href = $("#myletters").attr('href') + '#' + response.id;
                    			return false;
                    		}
                    		nextStep(5);
                    		currentStep = 6;
                    		if (currentStep > lastStep) lastStep = currentStep;
                    		$("#step5 div#error").hide();
                    		$("#step5 div#success").show();
                    		if (!generated) {
                    			var href = $("a#show").attr('href') + "/" + response.id;
                    			$("a#show").attr('href', href);
                    			href = $("a#download").attr('href') + "/" + response.id;
                    			$("a#download").attr('href', href);
                    			generated = true;
                    		}
                    	}
                    	else {
                			console.log(response);
                    		$(response).each(function () {
                    			if (this.message == 'generation') {
                    				nextStep(5);
                    				$("#step5 div#success").hide();
                    				$("#step5 div#error").show();
                    			}
                        });
                    	}
                    },
                    error: function(xhr, textStatus, errorThrown){
                        alert(textStatus + " // " + errorThrown);
                    }					
				});
				break;				
        	default:
        		console.log('error : ' + currentStep);
		}
    });

    $("button.prevStep").click(function() {
    	var currentStep = parseInt($(this).attr('rel'));
    	if (stepModified[currentStep+1] && !validate('step' + (currentStep+1))) {
    		return false;
    	}
    	prevStep(currentStep);
    });
});

function goToStep(numStep, originStep) {
	console.log('currentStep : ' + originStep + 'dest : ' + numStep + 'last : ' + lastStep);
	if (numStep <= lastStep) {
		if (numStep < originStep) {
			$("div#step"+originStep).hide("slide", { direction: "right" }, 500);
			$("li#step"+originStep).animate({ color: "#b0b1b3" }, 500).removeAttr("class");
			$("li#step"+numStep).animate({ color: "black" }, 500);
			if (numStep == 4) {
				$("div#step4").delay(500).show("slide", { direction: "left" }, 500, function() {
				    createEditor();
				});
			} 
			else if (originStep == 4) {
				removeEditor();
				$("div#step" + numStep).delay(500).show("slide", { direction: "left" }, 500);
			} 
			else {
				$("div#step"+numStep).delay(500).show("slide", { direction: "left" }, 500);
			}
			window.location.hash = "etape" + numStep;
		} else if (numStep > originStep) {
			$("div#step"+originStep).hide("slide", { direction: "left" }, 500);
			$("li#step"+originStep).animate({ color: "green" }, 500).removeAttr("class");
			$("li#step"+numStep).animate({ color: "black" }, 500);
			if (numStep == 4) { // besoin de créer l'éditeur quand on change de page 
				$("div#step4").delay(500).show("slide", { direction: "right" }, 500, function() {
					createEditor();
				});
			} 
			else if (originStep == 4) {
				removeEditor();
				$("div#step" + numStep).delay(500).show("slide", { direction: "right" }, 500, function() {});
			} else {
				$("div#step"+numStep).delay(500).show("slide", { direction: "right" }, 500, function() {});
			}
			window.location.hash = "etape" + numStep;
		}
	} else {
		console.log('refusé');
	}
}

function nextStep(numStep) {
	$("div#step"+(numStep-1)).hide("slide", { direction: "left" }, 500);
	$("li#step"+(numStep-1)).animate({ color: "green" }, 500).removeAttr("class");
	$("li#step"+(numStep)).wrap("<a href='' rel='" + numStep + "' />");
	$("li#step"+numStep).animate({ color: "black" }, 500);
	if (numStep == 4) { // besoin de créer l'éditeur quand on change de page 
		$("div#step4").delay(500).show("slide", { direction: "right" }, 500, function() {
			createEditor();
		});
	} 
	else if (numStep == 5) {
		removeEditor();
		$("div#step5").delay(500).show("slide", { direction: "right" }, 500, function() {
		});
	} else {
		$("div#step"+numStep).delay(500).show("slide", { direction: "right" }, 500, function() {
		});
	}
	window.location.hash = "etape" + numStep;
}

function prevStep(numStep) {
	$("div#step"+(numStep+1)).hide("slide", { direction: "right" }, 500);
	$("li#step"+(numStep+1)).animate({ color: "#b0b1b3" }, 500).removeAttr("class");
	$("li#step"+numStep).animate({ color: "black" }, 500);
	if (numStep == 1) {
		$("div#step"+numStep).delay(500).show("slide", { direction: "left" }, 500);
	} 
	else if (numStep == 4) {
		$("div#step4").delay(500).show("slide", { direction: "left" }, 500, function() {
		    createEditor();
		});
	} 
	else if (numStep == 3) {
		removeEditor();
		$("div#step3").delay(500).show("slide", { direction: "left" }, 500);
	} 
	else {
		$("div#step"+numStep).delay(500).show("slide", { direction: "left" }, 500);
	}
	window.location.hash = "etape" + numStep;
}

function createEditor() {
	return $("textarea#letter_add_contenu").cleditor({
        width:        790, // width not including margins, borders or padding
        height:       400, // height not including margins, borders or padding
        controls:     // controls to add to the toolbar
                      "undo redo | bold italic underline superscript | removeformat | bullets numbering | justify center | cut copy paste pastetext | source",  
        sizes:        // sizes in the font size popup
                      "1,2,3",
        styles:       // styles in the style popup
                      [["Paragraph", "<p>"], ["Header 1", "<h1>"], ["Header 2", "<h2>"],
                      ["Header 3", "<h3>"],  ["Header 4","<h4>"],  ["Header 5","<h5>"],
                      ["Header 6","<h6>"]],
        useCSS:       false, // use CSS to style HTML when possible (not supported in ie)
        docType:      // Document type contained within the editor
                      '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
        docCSSFile:   // CSS file used to style the document contained within the editor
                      "", 
        bodyStyle:    // style to assign to document body contained within the editor
                      "margin:4px; font:12px Verdana, Arial; cursor:text"
      });
}

function hideEditor() {
	var textarea = $('textarea#letter_add_contenu');
	var main = $('div.cleditorMain');
	textarea.insertBefore(main); 
	textarea.show();
	main.hide();
	//main.remove();
}

function removeEditor() {
	var textarea = $('textarea#letter_add_contenu');
	var main = $('div.cleditorMain');
	textarea.insertBefore(main); 
	textarea.show();
	$('textarea#letter_add_contenu').removeData();
	main.remove();
}

function showEditor() {
	$('div.cleditorMain').show();
}